package com.example.net

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


class RetrofitFactory private constructor() {
    companion object {
        private val instance: RetrofitFactory by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitFactory() }
        fun getRetrofitFactory(): RetrofitFactory {
            return instance
        }
        var token:String?=null
    }
    private val retrofit: Retrofit

    init {
        retrofit = Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_HOST)
            .client(createClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    private fun createClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(createLoggingInterceptor())
            .addInterceptor{it.proceed(token?.let { e-> it.request().newBuilder().addHeader("token",e).build() }?:it.request())}
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()
    }

    private fun createLoggingInterceptor(): Interceptor {
        return HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
    }



    fun <T>create(clazz: Class<T>):T =retrofit.create(clazz)
}